import React, { useEffect, useRef, useState, type KeyboardEvent } from 'react';

import MarkdownToPlainTextConverter from '@/components/MarkdownToPlainTextConverter';
import type { AiChatMessage } from '@/stores/ChatStores/type';
import { useStores } from '@/stores/hooks';
import {
  ClearOutlined,
  RobotOutlined,
  SendOutlined,
  UserOutlined,
} from '@ant-design/icons';
import {
  Avatar,
  Button,
  Card,
  Image,
  Input,
  Layout,
  Space,
  Spin,
  theme,
  Typography,
} from 'antd';
import dayjs from 'dayjs';
import { observer } from 'mobx-react';
import styles from './index.module.less';
const { Content } = Layout;
const { TextArea } = Input;
const { Text } = Typography;
// ==================== 类型定义 ====================
interface ChatProps {
  onSendMessage?: (message: string) => Promise<void>;
}

const Chat: React.FC<ChatProps> = observer(props => {
  const { onSendMessage } = props;
  const { chatStores } = useStores();
  const { token } = theme.useToken();
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const [value, setValue] = useState('');
  const lastContentLength =
    chatStores?.aiMessages[chatStores.aiMessages.length - 1]?.content.length;
  // ==================== 自动滚动 ====================
  // 自动滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };
  useEffect(() => {
    const timer = setTimeout(() => {
      scrollToBottom();
    }, 0);
    return () => clearTimeout(timer);
  }, [lastContentLength, chatStores?.aiMessages.length]);

  // ==================== 事件处理 ====================
  const handleKeyDown = (e: KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleAddChatContent();
    }
  };

  const handleAddChatContent = async () => {
    if (!value.trim()) return;
    const message: AiChatMessage = {
      role: 'user',
      timestamp: dayjs().toDate(),
      content: value,
      id: Date.now().toString(),
    };
    chatStores?.addContent(message);
    // 发送消息到服务器
    if (onSendMessage) {
      try {
        await onSendMessage(value);
      } catch (error) {
        console.error('发送消息失败:', error);
      }
    }
    setValue('');
    chatStores?.setIsLoading(true);
  };

  const renderChatContent = () => (
    <>
      {chatStores?.aiMessages.length === 0 && (
        <div className={styles.emptyState}>
          <RobotOutlined style={{ fontSize: '48px', color: '#d9d9d9' }} />
          <Text type='secondary'>开始与AI助手对话吧！</Text>
        </div>
      )}

      {chatStores?.aiMessages.map(message => (
        <div
          key={message.id}
          className={`${styles.message} ${
            message.role === 'user' ? styles.userMessage : styles.aiMessage
          }`}
        >
          <div className={styles.messageContent}>
            <div className={styles.messageHeader}>
              <Space>
                <Avatar
                  size='small'
                  icon={
                    message.role === 'user' ? (
                      <UserOutlined />
                    ) : (
                      <RobotOutlined />
                    )
                  }
                  style={{
                    backgroundColor:
                      message.role === 'user' ? '#1890ff' : '#52c41a',
                  }}
                />
                <Text strong style={{ color: '#000' }}>
                  {message.role === 'user' ? '你' : 'AI助手'}
                </Text>
                <Text type='secondary' style={{ fontSize: '12px' }}>
                  {dayjs(message.timestamp).format('YYYY-MM-DD HH:mm')}
                </Text>
              </Space>
            </div>
            <div className='message-body'>
              {message.isImage ? (
                <Image
                  src={message.content}
                  alt='AI生成的图片'
                  style={{ maxWidth: '100%', borderRadius: '8px' }}
                />
              ) : (
                <MarkdownToPlainTextConverter markdown={message.content} />
              )}
            </div>
          </div>
        </div>
      ))}

      {chatStores?.isLoading && (
        <div className={`${styles.message} ${styles.aiMessage}`}>
          <div className={styles.messageContent}>
            <div className={styles.messageHeader}>
              <Space>
                <Avatar
                  icon={<RobotOutlined />}
                  style={{ backgroundColor: '#52c41a' }}
                />
                <Text strong style={{ color: '#000' }}>
                  AI助手
                </Text>
              </Space>
            </div>
            <div className={styles.messageBody}>
              <Spin size='small' />
              <Text
                type='secondary'
                style={{ marginLeft: '8px', color: '#000' }}
              >
                正在思考...
              </Text>
            </div>
          </div>
        </div>
      )}

      <div ref={messagesEndRef} />
    </>
  );
  const renderInputArea = () => (
    <div
      className={styles.footerBox}
      style={{ background: token.colorBgElevated }}
    >
      <TextArea
        onKeyDown={handleKeyDown}
        value={value}
        onChange={e => setValue(e.target.value)}
        placeholder='输入你的问题... (按 Enter 发送)'
        autoSize={{ minRows: 3, maxRows: 3 }}
        disabled={chatStores?.isLoading}
        style={{
          background: chatStores?.theme === 'light' ? '#fff' : '#23272e',
          color: chatStores?.theme === 'light' ? '#222' : '#fff',
        }}
      />

      <Button
        type='primary'
        onClick={handleAddChatContent}
        disabled={!value.trim()}
        icon={<SendOutlined />}
        loading={chatStores?.isLoading}
        className={styles.sendButton}
      >
        发送
      </Button>

      <Button
        type='primary'
        icon={<ClearOutlined />}
        className={styles.sendButton}
        onClick={chatStores?.clearContent}
      >
        清空
      </Button>
    </div>
  );

  // ==================== 主渲染 ====================
  return (
    <div className={styles.chatContainer}>
      <Layout className={styles.layout}>
        <Content>
          <Card
            title={
              <Space>
                <RobotOutlined style={{ color: '#1890ff' }} />
                <span>AI 助手</span>
              </Space>
            }
            style={{ background: chatStores?.bgColor ?? token.colorBgElevated }}
            className={styles.chatCard}
          >
            {/* 聊天内容区域 */}
            <div className={styles.aiContent}>{renderChatContent()}</div>
          </Card>
        </Content>

        <footer>{renderInputArea()}</footer>
      </Layout>
    </div>
  );
});

export default Chat;
